import { Button, Drawer, Form, Input, message, Tree } from 'antd'
import type { roleType } from '@/types'
import React, { useEffect, useState } from 'react'
import { authCode } from '@/assets/dict/authCode'
import http from '@/utils/request'
import './index.scss'
import useuserInfoStore from '@/store/userInfo'

const roleDrawer: React.FC<{ isOpen: boolean, role?: roleType, onClose: (val:boolean) => void }> = ({ isOpen, role, onClose }) => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [checkedKeys, setCheckedKeys] = useState<string[]>([])
  const updateUserInfo = useuserInfoStore((state) => state.updateUserInfo)
  const userInfo = useuserInfoStore((state) => state.userInfo)

  useEffect(() => {
    setCheckedKeys(role?.permissionCode || [])
    form.resetFields()
  }, [role])

  const handleOk = () => {
    form?.validateFields()
      .then((values) => {
        setLoading(true)
        const url = role?.id ? '/disp/sys/role/update' : '/disp/sys/role/insert'
        http.post(url, {
          ...values,
          permissionCode: values.permissionCode.join(','),
          id: role?.id
        }).then(() => {
          message.success(`${role?.id ? '编辑' : '添加'}成功！`)
          updateUserInfo({
            ...userInfo,
            permissionCode: values.permissionCode.join(','),
            permissionCodes: values.permissionCode
          })
          onClose(true)
        }).catch(err => {
          message.error(err.msg || '操作失败')
        }).finally(() => {
          setLoading(false)
        })
      })
      .catch((errorInfo) => {
        console.log('校验失败:', errorInfo)
      })
  }
  const handleCancel = () => {
    onClose(false)
  }

  const handleTreeCheck = (check: any) => {
    setCheckedKeys(check.checked)
    form.setFieldsValue({
      permissionCode: check.checked
    })
  }

  return (<Drawer
    title={`${role?.id ? '编辑' : '添加'}角色`}
    closable={false}
    width={600}
    footer={
      <div className="button-container flex-row">
        <div className="flex1" />
        <Button onClick={handleCancel} className="btn">取 消</Button>
        <Button onClick={handleOk} loading={loading} className="btn" type="primary">保 存</Button>
      </div>
    }
    open={isOpen}>
    <div className="drawer-container flex-column">
      <Form
        form={form}
        initialValues={role || {}}
        style={{ maxWidth: 600, marginTop: 20 }}
        layout="vertical">
        <Form.Item<roleType>
          label="角色名称"
          name="roleName"
          rules={[{ required: true, message: '角色名称为空!' }]}
        >
          <Input
            allowClear
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item<roleType>
          label="权限点"
          name="permissionCode"
          rules={[{
            required: true,
            validator: (_, value) => {
              return value && value.length > 0 ? Promise.resolve() : Promise.reject(new Error('权限点不能为空!'))
            }
          }]}
        >
          <Tree
            checkable
            defaultExpandAll
            checkStrictly
            checkedKeys={checkedKeys}
            onCheck={handleTreeCheck}
            treeData={authCode}
          />
        </Form.Item>

        <Form.Item<roleType>
          label="备注"
          name="remark"
          rules={[{ required: false }]}
        >
          <Input
            allowClear
            style={{ width: '100%' }}
          />
        </Form.Item>
      </Form>
    </div>
  </Drawer>)
}

export default roleDrawer
